<template>
  <div class="avatar-uploader">
    <!-- 头像预览 -->
    <van-image
        width="200px"
        height="200px"
        fit="cover"
        round
        :src="previewAvatar || avatar"
    />

    <!-- 图片选择器（隐藏） -->
    <input
        type="file"
        ref="fileInput"
        accept="image/*"
        style="display: none"
        @change="handleFileChange"
    >

    <div class="upload-buttons">
      <!-- 上传按钮触发文件选择 -->
      <van-button
          type="primary"
          icon="photograph"
          @click="$refs.fileInput.click()"
          :loading="uploading1"
      >
        上传新头像
      </van-button>

      <!-- 确认上传按钮（仅在选择了新头像后显示） -->
      <van-button
          v-if="selectedFile"
          type="success"
          icon="success"
          @click="confirmUpload"
          :loading="uploading2"
      >
        修改头像
      </van-button>

      <!-- 退出按钮 -->
      <van-button
          type="default"
          @click="toggleUserInfoView"
          :disabled="uploading3"
      >
        放弃修改
      </van-button>
    </div>
  </div>
</template>

<script setup lang="ts" name="AvatarEditor">
import { ref } from 'vue';
import { showToast } from 'vant';
import { useUserStore } from '../../../Store/modules/userinfo/UserInfo.js'
import defaultAvatar from '../../../Assets/img/js_tx.webp';
import { showStore } from '../../../Store/modules/other/show'
import { updateUserUsingPost } from '../../../Api/yonghumokuai';
import { uploadUsingPost } from "../../../Api/wenjianshangchuanmokuai";
import router from "../../../Router";

const showStore1 = showStore();
const userStore = useUserStore();
const fileInput = ref<HTMLInputElement | null>(null);

// 当前头像
const avatar = ref(userStore.userInfo.userImage || defaultAvatar);
// 预览头像（新选择的）
const previewAvatar = ref('');
// 选择的文件
const selectedFile = ref<File | null>(null);
// 上传状态
const uploading1 = ref(false);
const uploading2 = ref(false);
const uploading3 = ref(false);

// 切换回用户信息视图
const toggleUserInfoView = () => {
  showStore1.updateshow(1);
  previewAvatar.value = '';
  selectedFile.value = null;
}

// 处理文件选择
const handleFileChange = (event: Event) => {
  const input = event.target as HTMLInputElement;
  if (input.files && input.files[0]) {
    // 验证文件类型
    const validTypes = ['image/jpeg', 'image/png', 'image/gif'];
    if (!validTypes.includes(input.files[0].type)) {
      showToast('请上传JPEG、PNG或GIF格式的图片');
      return;
    }

    // 验证文件大小 (2MB以内)
    if (input.files[0].size > 10 * 1024 * 1024) {
      showToast('图片大小不能超过10MB');
      return;
    }

    selectedFile.value = input.files[0];

    // 创建预览URL
    const reader = new FileReader();
    reader.onload = (e) => {
      previewAvatar.value = e.target?.result as string;
    };
    reader.readAsDataURL(selectedFile.value);
  }
};

// 确认上传头像
const confirmUpload = async () => {
  if (!selectedFile.value) return;

  uploading2.value = true;
  try {

    // 上传图片文件
    const uploadRes = await uploadUsingPost({
      file: selectedFile.value,
    });

    if (uploadRes.data.code === 0) {
      // 更新用户信息
      const updateRes = await updateUserUsingPost({
        userId: userStore.userInfo.userId,
        userImage: uploadRes.data.data
      });

      if (updateRes.data.code === 0) {
        showToast('头像上传成功');
        // 更新本地存储的头像
        userStore.updateUserInfo({
          ...userStore.userInfo,
          userImage: uploadRes.data.data?.url || previewAvatar.value
        });
        setTimeout(() => {
          // 返回用户信息页面
          toggleUserInfoView();
          // router.push('/cqust/userinfo')
        },500)
        // location.reload()
      } else {
        showToast(updateRes.data.message || '头像更新失败');
      }
    } else {
      showToast(uploadRes.data.message || '图片上传失败');
    }
  } catch (error) {
    console.error('上传头像出错:', error);
    showToast('上传过程中出错');
  } finally {
    uploading2.value = false;
    // 重置选择
    if (fileInput.value) {
      fileInput.value.value = '';
    }
    selectedFile.value = null;
  }
};
</script>

<style scoped>
.avatar-uploader {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
  background-color: #ffffff;
  padding: 20px;
}

.upload-buttons {
  margin-top: 20px;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 10px;
  width: 100%;
  max-width: 300px;
}

:deep(.van-button) {
  margin: 5px;
  flex: 1;
  min-width: 120px;
  border: none;
}

:deep(.van-button--primary) {
  background-color: rgb(83, 30, 88);
  color: white;
}

:deep(.van-button--success) {
  background-color: #07c160;
  color: white;
}

:deep(.van-button--default) {
  background-color: #f5f5f5;
  color: #333;
}

.van-image {
  margin-bottom: 20px;
  border: 5px solid #737373;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
  background-color: #f5f5f5;
}
</style>
